package com.caiheng.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.active.CommunityActive;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.sys.SysDictData;
import com.caiheng.api.entity.sys.SysNotice;
import com.caiheng.api.entity.titlemenu.TitleMenu;
import com.caiheng.api.entity.titlemenu.TitleMenuSection;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.active.CommunityActiveService;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.sys.SysDictDataService;
import com.caiheng.api.service.sys.SysNoticeService;
import com.caiheng.api.service.titlemenu.TitleMenuSectionService;
import com.caiheng.api.service.titlemenu.TitleMenuService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/index")//url:模块/资源/{}/细分
public class IndexPageController extends BaseController {
    @Resource
    private TitleMenuService titleMenuService;
    @Resource
    private TitleMenuSectionService titleMenuSectionService;
    @Resource
    private AdBannerService adBannerService;
    @Resource
    private SysNoticeService sysNoticeService;
    @Resource
    private UserService userService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private MapAreaService mapAreaService;
    @Resource
    private CityService cityService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private SysDictDataService sysDictDataService;
    @Resource
    private CommunityActiveService communityActiveService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址

    /**首页
     * @param
     * @throws Exception
     */
    @PostMapping(value="/index")
    public JSONObject indexPage(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<String, Object>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("index 接受参数：" + requestParam + "      " +  DateUtil.getTime());
            logger.info("index 接受参数：" + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id"): null;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex"): 1;
            int pageSize = jsonRequest.containsKey("pageSize") && StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize"): 20;
            double longitude = jsonRequest.containsKey("longitude") && StrUtil.isNotEmpty(jsonRequest.getStr("longitude")) ? jsonRequest.getDouble("longitude"): 0;
            double latitude = jsonRequest.containsKey("latitude") && StrUtil.isNotEmpty(jsonRequest.getStr("latitude")) ? jsonRequest.getDouble("latitude"): 0;

            int cityId = jsonRequest.containsKey("city_id") ? jsonRequest.getInt("city_id"): 0;
            String city_name = jsonRequest.containsKey("city_name") ? jsonRequest.getStr("city_name"): null;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform"): null;

            User user = null;
            if(user_id != null && user_id > 0){
                user  = userService.findById(user_id);
                if(user != null){
                    user.setLng(new BigDecimal(longitude));
                    user.setLat(new BigDecimal(latitude));

                    user = userService.getLocationInfo(user);
                    if(cityId > 0 && !user.getCity().equals(city_name)){
                        City city = cityService.findById(cityId);
                        if(city!=null){
                            Province province = provinceService.findById(city.getProvinceId());
                            if(province!=null){
                                user.setProvince(province.getProvinceName());
                            }
                        }
                        user.setCity(city_name);
                    }

                    boolean bl = mapAreaService.isInArea(user.getLng(),user.getLat(),0);
                    if(bl){
                        user.setIsCloseSign(0);
                    }else{
                        user.setIsCloseSign(1);
                    }
                    userService.updateById(user);
                }
            }

            List<AdBanner> banners = adBannerService.getList(1);
            map.put("banners",banners);

            //1.标题TAB菜单
            List<TitleMenu> menuList = new ArrayList<>();// titleMenuService.selectByState(0,1,0);
            if(user != null){
                //要判断是否 可以签到
                menuList = titleMenuService.selectByStateAndUser(user,0,1,0,platform);
            }else{
                menuList = titleMenuService.selectByState(0,1,0,platform);
            }

            map.put("menuList",menuList);

            map.put("rowCount", 4);//每行显示的数量
            map.put("propertyMenuRowCount",12);//每行显示的数量
            map.put("normalMenuRowCount",12);//每行显示的数量

            //2.自持项目菜单
//            List<TitleMenu> listNewUserMenu = titleMenuService.selectBySpecial("new_user");
//            map.put("listNewUserMenu",listNewUserMenu);
//            map.put("newUserMenuRowCount",4);//每行显示的数量

            map.put("is_change_location", 0);
            if(user != null && cityId == 0 && longitude > 0){
                //判断当前定位城市是否有变化
                Map<String,Object> blValidateLocation = userService.validateLocation(user);
//            blValidateLocation.put("is_change_location", bl ? 0 : 1);
//            blValidateLocation.put("now_address", address);
                map.putAll(blValidateLocation);
                map.put("city_name",user.getCity());
            }

            //3. 内容列表
            List<TitleMenuSection> sections = titleMenuSectionService.selectBySectionByLocation(user,pageIndex,pageSize,longitude,latitude,platform);
            map.put("sections",sections);

            List<SysNotice> notices = sysNoticeService.getList(user_id);
            map.put("notices",notices);

            map.put("is_show_search",0);
            map.put("is_show_platform_notice", 0);

            Parameter parameter = parameterService.getParameterById(1);
            if(parameter != null){
                map.put("is_show_search",parameter.getIsShowSearch());
                map.put("is_show_platform_notice",parameter.getIsShowPlatformNotice());
                map.put("platform_notice_img",parameter.getPlatformNoticeImg());
                map.put("first_page_filter_css",parameter.getFirstPageFilterCss());
            }

            List<SysDictData> activeTypeList = sysDictDataService.selectDictDataList("active_type");
            map.put("activeTypeList", activeTypeList);
            if(CollUtil.isNotEmpty(activeTypeList)){
                QueryWrapper<CommunityActive> qw = new QueryWrapper<>();
                qw.eq("active_type", activeTypeList.get(0).getDictValue());
                qw.eq("state",1 );
                qw.orderByDesc("create_time");
                qw.last("limit 5");
                List<CommunityActive> actives = communityActiveService.list(qw);
                if(CollUtil.isNotEmpty(actives)){
                    for (CommunityActive active : actives){
                        if(StrUtil.isNotEmpty(active.getPreviewImg())){
                            active.setPreviewImg(imgPrefix + active.getPreviewImg());
                        }
                    }
                }
                map.put("activeList", actives);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            e.printStackTrace();
            logger.error(e.toString(), e);
        }
        return result;
    }


    /**获取 内容行的 分页数据 只获取 内容行
     * @param
     * @throws Exception
     */
    @PostMapping(value="/notice/detail")
    public JSONObject noticeDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("getSectionList 接受参数：" + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id"): 0;
            int notice_id = jsonRequest.containsKey("notice_id") ? jsonRequest.getInt("notice_id"): 0;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
//            }

            SysNotice sysNotice = sysNoticeService.findById(notice_id);
            if(sysNotice!=null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",sysNotice),true,false);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"信息异常"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.toString(), e);
        }
        return result;
    }


    /**获取 内容行的 分页数据 只获取 内容行
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getSectionList")
    public JSONObject getSectionList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("getSectionList 接受参数：" + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int title_menu_id = jsonRequest.containsKey("title_menu_id") ? jsonRequest.getInt("title_menu_id"): 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex"): 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize"): 20;
            Map<String,Object> map = new HashMap<>();
            TitleMenu titleMenu = titleMenuService.findById(title_menu_id);
            if(titleMenu!=null) {
                if (titleMenu.getState() == 0) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前页已关闭"), true, true);
                }
                //2. 内容列表
                QueryWrapper<TitleMenuSection> qw0 = new QueryWrapper<>();
                qw0.eq("title_menu_id",title_menu_id);
                List<TitleMenuSection> sections = titleMenuSectionService.getPageEntityList(qw0, pageIndex, pageSize);
                map.put("sections", sections);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "成功", map), true, false);
            }else{
                Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前页不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.toString(), e);
        }
        return result;
    }
}
